package com.itheima.controller;

import com.itheima.pojo.Book;
import com.itheima.pojo.Result;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        try {
            bookService.save(book);
            return new Result(null,true,"保存成功");
        } catch (Exception e) {
            return new Result(null,false,"保存失败");
        }
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        try {
            bookService.update(book);
            return new Result(null,true,"修改成功");
        } catch (Exception e) {
            return new Result(null,false,"修改失败");
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        try {
            bookService.delete(id);
            return new Result(null,true,"删除成功");
        } catch (Exception e) {
            return new Result(null,false,"删除失败");
        }
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        try {
            Book book = bookService.getById(id);
            return new Result(book,true,"查询成功");
        }
        catch (Exception io) {
            return new Result(null, false, "查询失败");
        }
    }

    @GetMapping
    public Result getAll() {
        try {
            List<Book> books = bookService.getAll();
            return new Result(books,true,"查询成功");
        } catch (Exception e) {
            return new Result(null,false,"查询失败");
        }

    }

}
